﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
using UnityEditor;
using UnityEditor.U2D;
using Framework.Define;

namespace FrameworkEditor.UITools.UIGenerate
{
    public class UIGenerateTextureAndAtlas : UIGenerateBase
    {
        private string mUIName = string.Empty;
        private string mAtlasFileName = string.Empty;

        private bool mIsSubPanel = false;
        private string mMainPanelName = string.Empty;

        public UIGenerateTextureAndAtlas(string pUIName, bool pIsSubPanel, string pMainPanelName)
        {
            mUIName = pUIName;
            mAtlasFileName = string.Format("Atlas_{0}.spriteatlas", mUIName);

            mIsSubPanel = pIsSubPanel;
            if (!mIsSubPanel)
                mMainPanelName = pUIName;
            else
                mMainPanelName = pMainPanelName;
        }

        public void GenerateTextureAndAtlas()
        {
            CreateTextureDirectory();

            string atlasFileFullPath = string.Format("{0}/{1}/{2}/Atlas/{3}", Application.dataPath, FrameworkDefine.UIRootDirectoryPath, mMainPanelName, mAtlasFileName);
            if (CheckExistFile(atlasFileFullPath, mAtlasFileName))
            {
                string atlasDirectoryPath = string.Format("{0}/{1}/{2}/Atlas", Application.dataPath, FrameworkDefine.UIRootDirectoryPath, mMainPanelName);
                CreateDirectory(atlasDirectoryPath);
                CreateAtlas();
            }
        }

        private void CreateTextureDirectory()
        {
            string textureDirectoryPath = string.Format("{0}/{1}/{2}/Textures/{3}", Application.dataPath, FrameworkDefine.UIRootDirectoryPath, mMainPanelName, mUIName);
            CreateDirectory(textureDirectoryPath);
            AssetDatabase.Refresh();
            Debug.Log(string.Format("{0} Texture Directory create succeed. File path is:{1}", mUIName, textureDirectoryPath));
        }

        private void CreateAtlas()
        {
            SpriteAtlas spriteAtlas = new SpriteAtlas();
            SpriteAtlasPackingSettings packSetting = new SpriteAtlasPackingSettings()
            {
                blockOffset = 1,
                enableRotation = false,
                enableTightPacking = false,
                padding = 4,
            };
            spriteAtlas.SetPackingSettings(packSetting);

            string textureRelativePath = string.Format("Assets/{0}/{1}/Textures/{2}", FrameworkDefine.UIRootDirectoryPath, mMainPanelName, mUIName); ;
            Object obj = AssetDatabase.LoadAssetAtPath(textureRelativePath, typeof(Object));
            spriteAtlas.Add(new[] { obj });

            string atlasFileRelativePath = string.Format("Assets/{0}/{1}/Atlas/{2}", FrameworkDefine.UIRootDirectoryPath, mMainPanelName, mAtlasFileName);
            AssetDatabase.CreateAsset(spriteAtlas, atlasFileRelativePath);
        }
    }
}